const Base = require("./base.js");

module.exports = class extends Base {
  /**
   * 列表
   * @param name
   * @returns {Promise<any>}
   */
  async indexAction() {
    const sT = Date.now();
    const post = this.post();
    const db = this.model("config");
    const result = {};
    result.errno = 0;
    result.data = await db.list(post);
    result.time = Date.now() - sT;
    return this.json(this.format(result));
  }

  /**
   * 删除
   * @param id
   * @returns {Promise<void>}
   */
  async delAction() {
    const post = this.post();
    const sT = Date.now();
    const db = this.model("config");
    const result = {};
    try {
      await db.del(post.id);
      result.errno = 0;
    } catch (e) {
      result.errno = -1;
      result.errmsg = e.toString();
    }
    result.time = Date.now() - sT;
    return this.json(this.format(result));
  }

  /**
   * 添加
   * @returns {Promise<any>}
   */
  async addAction() {
    const sT = Date.now();
    const post = this.post();
    const db = this.model("config");
    const result = {};
    try {
      await db.add(post);
      result.errno = 0;
    } catch (e) {
      result.errno = -1;
      result.errmsg = e.toString();
    }
    result.time = Date.now() - sT;
    return this.json(this.format(result));
  }

  /**
   * 详情
   * @returns {Promise<any>}
   */
  async detailAction() {
    const sT = Date.now();
    const { id, key } = this.post();
    const db = this.model("config");
    const result = {};
    try {
      result.errno = 0;
      const cacheKey = id || key || "";
      const cacheService = this.service("cache/key");
      await cacheService.set("CONFIG_" + cacheKey, cacheKey);
      const data = await this.cache("CONFIG_" + cacheKey);
      if (data && data.id) {
        result.data = Object.assign({}, data, { cache: true });
      } else {
        result.data = await db.detail({ id, key });
        await this.cache("CONFIG_" + cacheKey, result.data);
      }
    } catch (e) {
      result.errno = -1;
      result.errmsg = e.toString();
    }
    result.time = Date.now() - sT;
    return this.json(this.format(result));
  }

  /**
   * 修改
   * @returns {Promise<any>}
   */
  async updateAction() {
    const sT = Date.now();
    const post = this.post();
    const db = this.model("config");
    const result = {};
    const { id, key } = post;
    if (id) await this.cache("CONFIG_" + id, null);
    if (key) await this.cache("CONFIG_" + key, null);
    try {
      result.errno = 0;
      result.data = await db.where({ id: post.id }).update(post);
    } catch (e) {
      result.errno = -1;
      result.errmsg = e.toString();
    }
    result.time = Date.now() - sT;
    return this.json(this.format(result));
  }
};
